import axios from "axios";
import Cookies from "js-cookie";
import router from "../router";
import resetMessage from "@/utils/resetMessage";
const service = axios.create({
  // 后端线上地址
  baseURL: "http://121.40.61.6:3007",
  // 后端本地地址
  // baseURL: "http://127.0.0.1:3007",
  withCredentials: false,
  timeout: 1000000000,
  headers: {
    // 'Content-Type': 'application/json'
    "Content-Type": "application/x-www-form-urlencoded",
  },
});

service.interceptors.request.use(
  (config) => {
    if (Cookies.get("token")) {
      config.headers.Authorization = Cookies.get("token");
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use((response) => {
  if (response.data.status === 0) {
    return Promise.resolve(response);
  } else if (response.data.status === 1) {
    resetMessage.error(response.data.message);
  } else if (response.data.status === 3) {
    resetMessage.error(response.data.message);
    setTimeout(() => {
      router.push("/login");
    }, 3000);
  } else {
    resetMessage.error(response.data.message);
  }
  return Promise.resolve(response);
});

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    service
      .get(url, {
        params: params,
      })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}
/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post(url, data = {}, config = {}) {
  return new Promise((resolve, reject) => {
    service
      .post(url, data, config)
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}
/**
 * patch方法，对应patch请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function patch(url, data = {}) {
  return new Promise((resolve, reject) => {
    service
      .patch(url, data)
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}
/**
 * delete方法，对应delete请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function Delete(url, params = {}) {
  return new Promise((resolve, reject) => {
    service
      .delete(url, {
        params: params,
      })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}
